package com.chenggcode.security.jwt.controller;

import com.chenggcode.security.jwt.entity.AuthRequest;
import com.chenggcode.security.jwt.entity.UserInfo;
import com.chenggcode.security.jwt.service.UserInfoService;
import com.chenggcode.security.jwt.service.impl.JwtService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author Chenggcode
 * @date 2025/7/7 16:03
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
    private final JwtService jwtService;
    private final UserInfoService service;
    private final AuthenticationManager authenticationManager;

    @GetMapping("/welcome")
    public String welcome() {
        return "Welcome this endpoint is not secure";
    }

    @PostMapping("/addNewUser")
    public String addNewUser(@RequestBody UserInfo userInfo) {
        service.addUser(userInfo);
        return "User added successfully!";
    }

    @PostMapping("/generateToken")
    public Map<String, String> authenticateAndGetToken(@RequestBody AuthRequest authRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())
        );
        if (authentication.isAuthenticated()) {
            return jwtService.geneToken(authRequest.getUsername());
        } else {
            throw new UsernameNotFoundException("Invalid user request!");
        }
    }

    @PostMapping("/disableRefreshToken")
    public String disableRefreshToken(@RequestParam String username) {
        jwtService.disableRefreshToken(username);
        return "Refresh token disabled successfully!";
    }

    @GetMapping("/refreshToken")
    public String refreshToken(@RequestParam String refreshToken) {
        return jwtService.refreshToken(refreshToken);
    }
}
